<?php
/**
 * Created by PhpStorm.
 * User:lll
 * Date: 2018/12/01
 * Time: 下午5:22
 */
namespace app\common\model;

use think\Db;
class Ordershop extends Common
{
    /**
     * 会员添加购物车
     * @param $user_id
     * @param $goods_id
     * @param $spec_id
     * @param $num
     * @return string
     * @throws UserException
     */
    static public function addCar($user_id,$goods_id,$spec_id,$num){

        if(empty($num)){
            throw new UserException('请选择商品数量！');
        }
        $info = Goodssell::check($goods_id);
        $where = ['uid'=>$user_id,'goods_id'=>$goods_id,'spec_id'=>$spec_id];
        $exist = Db::name('sell_goods_car')->where($where)->find();
        if($exist){
            $total = $exist['num']+$num;
        }else{
            $count = Db::name('sell_goods_car')->where('uid',$user_id)->count();
            if($count>=config('car_max')){
                throw new UserException('已达到购物车容量限制'.config('car_max').'件，请清理部分再来添加！');
            }
            $total = $num;
        }

        if($info['use_spec']==1){
            if(empty($spec_id)){
                $str = empty($info['spec_name']) ? '规格' : $info['spec_name'];
                throw new UserException('请选择'.$str.'！');
            }
            $spec = Db::name('sell_goods_spec')->where(['id'=>$spec_id,'goods_id'=>$goods_id])->find();
            if(!$spec){
                throw new UserException('该规格商品已下架！');
            }

            if($spec['stock']<$total){
                throw new UserException('该规格商品库存不足！');
            }
        }else{
            if(!empty($spec_id)){
                throw new UserException('该商品已关闭规格，请刷新商品后重新选择');
            }
            if($info['stock']<$total){
                throw new UserException('该商品库存不足！');
            }
        }

        //限购
        $maxbuy = $info['maxbuy'];//单次
        $allbuy = $info['allbuy'];//每人总共

        $user_allbuy = self::userAllBuy($user_id,$goods_id);
        $total2 = $total+$user_allbuy;
        if($exist){

            if($maxbuy>0 && $total>$maxbuy){
                throw new UserException('该商品每次限购'.$maxbuy.'件！购物车中已有'.$exist['num'].'件！');
            }
            if($allbuy>0 && $total2>$allbuy){
                $strs = '该商品每人限购'.$allbuy.'件！购物车中已有'.$exist['num'].'件！';
                if(!empty($user_allbuy)){
                    $strs .= '已下单'.$user_allbuy.'件！';
                }
                throw new UserException($strs);
            }
            $data=[
                'update_time'=>now_datetime(),
                'num'=>$total
            ];
            Db::name('sell_goods_car')->where($where)->update($data);
        }else{
            if($maxbuy>0 && $total>$maxbuy){
                throw new UserException('该商品每次限购'.$maxbuy.'件！');
            }
            if($allbuy>0 && $total2>$allbuy){
                $strs = '该商品每人限购'.$allbuy.'件！';
                if(!empty($user_allbuy)){
                    $strs .= '已下单'.$user_allbuy.'件！';
                }
                throw new UserException($strs);
            }
            $data=[
                'uid'=>$user_id,
                'goods_id'=>$goods_id,
                'spec_id'=>$spec_id,
                'num'=>$num,
                'create_time'=>now_datetime(),
                'update_time'=>now_datetime(),
            ];
            Db::name('sell_goods_car')->insert($data);
        }

        return '添加购物车成功';

    }

    /**
     * 获取会员已购某件商品的总数
     * @param $user_id
     * @param $goods_id
     * @return float|int
     */
    static public function userAllBuy($user_id,$goods_id){
        $user_allbuy = Db::name('sell_order_goods')
            ->alias('og')
            ->join('sell_order o','o.id=og.orderid','left')
            ->where('og.uid',$user_id)
            ->where('og.goods_id',$goods_id)
            ->where('o.status','egt',1)
            ->sum('og.num');
        $user_allbuy = empty($user_allbuy) ? 0 : $user_allbuy;
        return $user_allbuy;
    }

    /**
     * 会员购物车列表
     * @param $user_id
     */
    static public function carList($user_id){
        $list = Db::name('sell_goods_car')
            ->alias('gc')
            ->join('sell_goods gs','gs.id=gc.goods_id','LEFT')
            ->where('gc.uid',$user_id)
            ->order('gc.id DESC')
            ->field("gc.spec_id,gs.status,gs.stock,gc.id as car_id,gs.id as goods_id,gs.img_url,gs.title,gs.price,gs.use_spec,gc.num")
            ->select();
        $car_remove = false;
        foreach ($list as $keys=>&$items) {
            if($items['status']!=1||$items['stock']<=0){
                //已下架或库存不足
                //删除购物车对应
                Db::name('sell_goods_car')->where(['id'=>$items['car_id'],'uid'=>$user_id])->delete();
                //去掉此条数据
                unset($list[$keys]);
                $car_remove = true;
                continue;
            }
            $items['spec_title'] = '';
            if($items['use_spec']==1){
                $spec = Db::name('sell_goods_spec')->where('id',$items['spec_id'])->find();
                if(!$spec||$spec['stock']<=0){
                    //商品规格有误
                    //删除购物车对应
                    Db::name('sell_goods_car')->where(['id'=>$items['car_id'],'uid'=>$user_id])->delete();
                    //去掉此条数据
                    unset($list[$keys]);
                    $car_remove = true;
                    continue;
                }
                $items['img_url'] = $spec['img_url'];
                $items['spec_title'] = $spec['title'];
                $items['price'] = $spec['price'];
            }else{
                if(!empty($items['spec_id'])){
                    //商品关闭了规格 而此购物车 是有规格时选择的
                    Db::name('sell_goods_car')->where(['id'=>$items['car_id'],'uid'=>$user_id])->delete();
                    //去掉此条数据
                    unset($list[$keys]);
                    $car_remove = true;
                    continue;
                }
            }
        }
        $tag = $car_remove==true?'售罄的商品已被自动清除':'';
        $arr = [
            'tag'=>$tag,
            'data'=>$list
        ];

        return $arr;
    }

    /**
     * 购物车商品删除
     * @param $user_id
     * @param $del_id
     * @return string
     */
    static public function carRemove($user_id,$del_id){
        $del_id = explode(',',$del_id);
        foreach ($del_id as $key=>$item){
            if(empty($item)){
                unset($del_id[$key]);
            }
        }
        if(count($del_id)<=0){
            throw new UserException('请选择要删除的商品！');
        }
        Db::name('sell_goods_car')
            ->where('uid',$user_id)
            ->where('id','in',$del_id)
            ->delete();
        return '删除商品成功';
    }

    /**
     * 购物车商品数量增减
     * @param $user_id
     * @param $type
     * @param $car_id
     * @param int $num
     * @return string
     * @throws DeveloperException
     * @throws UserException
     */
    static public function carAddDelete($user_id,$type,$car_id,$num=1){
        $car = Db::name('sell_goods_car')
            ->alias('gc')
            ->join('sell_goods g','g.id=gc.goods_id','LEFT')
            ->where('gc.id',$car_id)
            ->where('gc.uid',$user_id)
            ->field('gc.num,gc.goods_id,gc.spec_id,g.status,g.stock,g.use_spec,g.minbuy,g.maxbuy,g.allbuy')
            ->find();
        if(!$car){
            throw new UserException('无此购物车记录，请清理此条记录后再操作！');
        }

        if($car['status']!=1){
            throw new UserException('该商品已下架！');
        }

        if($car['stock']<=0){
            throw new UserException('该商品已售罄！');
        }

        if($car['use_spec']==1){
            if(empty($car['spec_id'])){
                throw new UserException('该商品已启用规格！请清理后重新选择！');
            }

            $spec = Db::name('sell_goods_spec')->where(['id'=>$car['spec_id'],'goods_id'=>$car['goods_id']])->find();
            if(!$spec){
                throw new UserException('该规格商品已下架！请清理后重新选择！');
            }

            if($spec['stock']<=0){
                throw new UserException('该规格商品已售罄！请清理后重新选择！');
            }

        }else{
            $spec=false;
        }

        if($type==0){
            //减
            $num_total = $car['num']-1;
            if($car['minbuy']>0 && $num_total<$car['minbuy']){
                throw new UserException('该商品'.$car['minbuy'].'件起售，不能再减了！');
            }
            if($num_total<1){
                throw new UserException('就剩1件了，不能再减了！');
            }
        }elseif($type==1){
            //加
            $num_total = $car['num']+1;
            if(!$spec){
                if($car['stock']<$num_total){
                    throw new UserException('该商品库存不足，不能再加了！');
                }
            }else{
                if($spec['stock']<$num_total){
                    throw new UserException('该规格商品库存不足，不能再加了！');
                }
            }

            if($car['maxbuy']>0 && $num_total>$car['maxbuy']){
                throw new UserException('该商品每次限购'.$car['maxbuy'].'件，不能再加了！');
            }

            if($car['allbuy']>0){
                $user_allbuy = self::userAllBuy($user_id,$car['goods_id']);
                $all = $num_total+$user_allbuy;
                if($all>$car['allbuy']){
                    $strs = '该商品每人限购'.$car['allbuy'].'件';
                    if($user_allbuy>0){
                        $strs .= '已下单'.$user_allbuy.'件，';
                    }
                    $strs .= '，不能再加了！';
                    throw new UserException($strs);
                }
            }

        }else{
            throw new DeveloperException('type仅支持0或1 0减1加');
        }

        $data = [
            'update_time'=>now_datetime(),
            'num'=>$num_total
        ];

        Db::name('sell_goods_car')
            ->where('id',$car_id)
            ->where('uid',$user_id)
            ->update($data);

        if($type==0){
            return '减少成功';
        }else{
            return '增加成功';
        }
    }

    /**
     * 确认订单
     * @param $user
     * @param $data
     * @param int $type 1购物车  2立即购买
     * @return array
     * @throws UserException
     * @throws \app\common\model\DeveloperException
     */
    static public function carConfirmOrder($user,$data,$type=1){
        if(!is_array($data)){
            throw new DeveloperException('data数据格式有误');
        }

        if(count($data)<=0){
            throw new UserException('商品为空，请选择您要购买的商品！');
        }

        $key = 0;//第几件
        $goods_total = 0;//共多少
        $goods_price = 0;//商品费用
        $dispatch_price = 0;//总运费
        $dispatch_detail = [];//运费详情
        $goods_id = 0;//上一件商品id
        $last_num = 0;//上一件同一不同规格商品买了多少件
        $userAllBuy = 0;//已经下单多少
        $maxCoin = 0;//必须使用 要么用 要么不用  用就能达到这个量
        foreach ($data as &$item){
            $key++;

            if($type==1&&!isset($item['car_id'])){
                throw new DeveloperException('data下car_id参数缺失');
            }
            if(!isset($item['goods_id'])){
                throw new DeveloperException('data下goods_id参数缺失');
            }

            if(!isset($item['num'])){
                throw new DeveloperException('data下num参数缺失');
            }

            if($item['num']<1){
                throw new UserException('最少购买一件！');
            }

            $goods = Db::name('sell_goods')
                ->where('id',$item['goods_id'])
                ->find();

            //组织数据
            $item['img_url'] = $goods['img_url'];
            $item['title'] = $goods['title'];
            $item['spec_title'] = '';
            $item['price'] = $goods['price'];
//            $item['can_coin']=$goods['can_coin'];

            if(!$goods){
                if($type==1){
                    throw new  UserException('第'.$key.'件商品已下架！');
                }else{
                    throw new  UserException('该商品已下架！');
                }
            }

            if($goods['status']!=1){
                throw new  UserException('商品'.$goods['title'].'已下架！');
            }

            if($goods['stock']<=0){
                throw new  UserException('商品'.$goods['title'].'已售罄！');
            }
            if($goods['use_spec'] == 1){
                if(empty($item['spec_id'])){
                    throw new  UserException('商品'.$goods['title'].'已启用规格，请重新选择！');
                }
                $spec = Db::name('goods_spec')->where(['id'=>$item['spec_id'],'goods_id'=>$item['goods_id']])->find();
                if(!$spec){
                    throw new  UserException('商品'.$goods['title'].'无此规格，请重新选择！');
                }
                if($spec['stock']<$item['num']){
                    throw new  UserException('商品'.$goods['title'].'+'.$spec['title'].'，库存不足，剩余'.$spec['stock'].'件！');
                }
                //启用规格重新组织数据
                $item['img_url'] = $spec['img_url'];
                $item['spec_title'] = $spec['title'];
                $item['price'] = $spec['price'];
            }else{
                if(!empty($item['spec_id'])){
                    throw new  UserException('商品'.$goods['title'].'已关闭规格，请重新选择！');
                }
                if($goods['stock']<$item['num']){
                    throw new  UserException('商品'.$goods['title'].'，库存不足，剩余'.$goods['stock'].'件！');
                }
            }

            $minbuy = $goods['minbuy'];
            if($minbuy>0 && $item['num']<$minbuy){
                throw new  UserException('商品'.$item['title'].'，'.$minbuy.'件起售！');
            }
            $maxbuy = $goods['maxbuy'];
            $allbuy = $goods['allbuy'];

            //n件商品
            $goods_total += $item['num'];
            //商品小计价格
            $goods_price += $item['price']*$item['num'];
            if($item['goods_id']==$goods_id){
                //和上一件是同一商品 不考虑规格
                if($goods['dispatch_type']==1){
                    //统一运费 多件只取一件
                    $goods_dispatch = 0;
                }else{
                    //按件 每件一次
                    $goods_dispatch = $goods['dispatch_price']*$item['num'];
                }
                $last_num += $item['num'];
                if($maxbuy>0 && $last_num>$maxbuy){
                    throw new  UserException('商品'.$item['title'].'，每次限购'.$maxbuy.'件！');
                }
                if($allbuy>0){
                    if(($last_num+$userAllBuy)>$allbuy){
                        throw new  UserException('商品'.$item['title'].'，每人限购'.$allbuy.'件！');
                    }
                }
            }else{
                //和上一件不是同一商品 不考虑规格
                $goods_id=$item['goods_id'];
                if($goods['dispatch_type']==1){
                    //统一运费 多件只取一件
                    $goods_dispatch = $goods['dispatch_price'];
                }else{
                    //按件 每件一次
                    $goods_dispatch = $goods['dispatch_price']*$item['num'];
                }
                if($maxbuy>0 && $item['num']>$maxbuy){
                    throw new  UserException('商品'.$item['title'].'，每次限购'.$maxbuy.'件！');
                }
                $last_num=$item['num'];
                if($allbuy>0){
                    $userAllBuy = self::userAllBuy($user['id'],$item['goods_id']);
                    if(($item['num']+$userAllBuy)>$allbuy){
                        throw new  UserException('商品'.$item['title'].'，每人限购'.$allbuy.'件！');
                    }
                }
            }

            //可用购物积分 每件价格*抵扣比例*件数
//            $maxCoin += $item['price']*$item['can_coin']/100*$item['num'];

            //运费详情
            $dispatch_detail[] = [
                'title'=>$item['title'].' '.$item['spec_title'],
                'price'=>'￥'.$goods_dispatch
            ];
            //总运费
            $dispatch_price += $goods_dispatch;
        }

        $maxCoin = round($maxCoin,2);

//        $rate = Settings::getRate();
//        if($dispatch_price>0 && $rate['is_full_free']==1){
//            if($goods_price>=$rate['full_money']){
//                //运费详情
//                $dispatch_detail[] = [
//                    'title'=>'满'.$rate['full_money'].'包邮',
//                    'price'=>'- ￥'.$dispatch_price
//                ];
//                $dispatch_price = 0;
//            }
//        }


        //订单总价 不使用 购物积分
        $no_use_coin_price = $goods_price+$dispatch_price;
//        $use_coin = self::calUseCoin($maxCoin,$user['coin'],$no_use_coin_price);//可以用多少购物积分
        $use_coin = 0;
        $use_coin_price = $no_use_coin_price-$use_coin;//购物积分抵扣后订单总价  总价 - 购物积分

        $arr = [
            'address'=>[
                'has_address'=>0,
                'address_id'=>'',
                'name'=>'',
                'mobile'=>'',
                'pro_id'=>'',
                'city_id'=>'',
                'area_id'=>'',
                'pca'=>'',
                'detail'=>'',
                'is_def'=>0,
            ],
            'goods'=>$data,
            'dispatch_price'=>$dispatch_price,
            'dispatch_detail'=>$dispatch_detail,
            'goods_total'=>$goods_total,
            'goods_price'=>$goods_price,
            'use_coin'=>$use_coin,
            'use_coin_price'=>$use_coin_price,
            'no_use_coin_price'=>$no_use_coin_price
        ];

        $address = Region::userAddress($user['id']);

        if($address){
            $arr ['address'] = $address;
        }

        return $arr;
    }

    /**
     * 计算可以使用多少购物积分
     * @param $maxCoin float 必须使用
     * @param $userCoin float 自己有多少
     * @param $orderPrice float 订单价格
     */
    static public function calUseCoin($maxCoin,$userCoin,$orderPrice){
        if($maxCoin>$userCoin){
            $coin = 0;//必须使用的量  比 自己的多 那么就不能用
        }else{
            $coin = $maxCoin;//自己的比最多使用要多或相等  那么可以使用 最多
        }
        //判断一下
        if($coin>=$orderPrice){
            $coin = $orderPrice;
        }
        return $coin;
    }

    /**
     * 地址验证
     * @param $address
     * @return array
     * @throws UserException
     */
    static public function checkAddress($address){
        $address = explode(' ',$address);
        if(count($address)<4){
            throw new UserException('收货地址有误，请重新选择');
        }
        $proid = Db::name('region')
            ->where('level',1)
            ->where('title','like',"%".$address[0]."%")
            ->value('id');
        if(empty($proid)){
            throw new UserException('收货地址有误，请重新选择');
        }

        $cityid = Db::name('region')
            ->where('parent_id',$proid)
            ->where('title','like',"%".$address[1]."%")
            ->value('id');
        if(empty($cityid)){
            throw new UserException('收货地址有误，请重新选择');
        }

        $areaid = Db::name('region')
            ->where('parent_id',$cityid)
            ->where('title','like',"%".$address[2]."%")
            ->value('id');
        if(empty($areaid)){
            throw new UserException('收货地址有误，请重新选择');
        }

        return [
            'proid'=>$proid,
            'cityid'=>$cityid,
            'areaid'=>$areaid
        ];
    }

    /**
     * 提交订单来自购物车
     * @param $user
     * @param $message
     * @return array
     * @throws DeveloperException
     * @throws UserException
     */
    static public function carSubOrder($user,$message){

        $arr = getTemporary($user);
        if(!$arr){
            throw new DeveloperException('订单数据有误');
        }
        $addArr = $arr['confirm']['address'];
        $data = $arr['subData'];
        $type = $arr['subType'];

        if($addArr['has_address']!=1||empty($addArr['address_id'])){
            throw new UserException('请选择收货地址！');
        }

        if(!is_array($data)){
            throw new DeveloperException('data数据格式有误');
        }

        if(count($data)<=0){
            throw new UserException('商品为空，请选择您要购买的商品！');
        }

        $key = 0;//第几件
        $goods_total = 0;//共多少
        $goods_price = 0;//商品费用
        $dispatch_price = 0;//总运费

        $goods_id = 0;//上一件商品id
        $last_num = 0;//上一件同一不同规格商品买了多少件
        $userAllBuy = 0;//已经下单多少
        $maxCoin = 0;//必须达到这个购物积分 才可用
        $is_vip = 0;//是否含有可升级vip商品
        $send_coin = 0;//赠送购物积分
        $send_sugar = 0;//赠送消费积分
        foreach ($data as &$item){
            $key++;

            if($type==1&&!isset($item['car_id'])){
                throw new DeveloperException('data下car_id参数缺失');
            }
            if(!isset($item['goods_id'])){
                throw new DeveloperException('data下goods_id参数缺失');
            }

            if(!isset($item['num'])){
                throw new DeveloperException('data下num参数缺失');
            }

            if($item['num']<1){
                throw new UserException('最少购买一件！');
            }

            $goods = Db::name('sell_goods')
                ->where('id',$item['goods_id'])
                ->find();

            //组织数据
            $item['img_url'] = $goods['img_url'];
            $item['title'] = $goods['title'];
            $item['spec_title'] = '';
            $item['price'] = $goods['price'];
//            $item['is_vip'] = $goods['is_vip'];
            $item['can_coin']=$goods['can_coin'];
            $item['send_coin'] = 0;
            $item['send_sugar'] = 0;

            if(!$goods){
                if($type==1){
                    throw new  UserException('第'.$key.'件商品已下架！');
                }else{
                    throw new  UserException('该商品已下架！');
                }
            }

            if($goods['status']!=1){
                throw new  UserException('商品'.$goods['title'].'已下架！');
            }

            if($goods['stock']<=0){
                throw new  UserException('商品'.$goods['title'].'已售罄！');
            }
            if($goods['use_spec'] == 1){
                if(empty($item['spec_id'])){
                    throw new  UserException('商品'.$goods['title'].'已启用规格，请重新选择！');
                }
                $spec = Db::name('sell_goods_spec')->where(['id'=>$item['spec_id'],'goods_id'=>$item['goods_id']])->find();
                if(!$spec){
                    throw new  UserException('商品'.$goods['title'].'无此规格，请重新选择！');
                }
                if($spec['stock']<$item['num']){
                    throw new  UserException('商品'.$goods['title'].'+'.$spec['title'].'，库存不足，剩余'.$spec['stock'].'件！');
                }
                //启用规格重新组织数据
                $item['img_url'] = $spec['img_url'];
                $item['spec_title'] = $spec['title'];
                $item['price'] = $spec['price'];
            }else{
                if(!empty($item['spec_id'])){
                    throw new  UserException('商品'.$goods['title'].'已关闭规格，请重新选择！');
                }
                if($goods['stock']<$item['num']){
                    throw new  UserException('商品'.$goods['title'].'，库存不足，剩余'.$goods['stock'].'件！');
                }
            }

            $minbuy = $goods['minbuy'];
            if($minbuy>0 && $item['num']<$minbuy){
                throw new  UserException('商品'.$item['title'].'，'.$minbuy.'件起售！');
            }
            $maxbuy = $goods['maxbuy'];
            $allbuy = $goods['allbuy'];

            //n件商品
            $goods_total += $item['num'];
            //商品小计价格
            $goods_price += $item['price']*$item['num'];
            if($item['goods_id']==$goods_id){
                //和上一件是同一商品 不考虑规格
                if($goods['dispatch_type']==1){
                    //统一运费 多件只取一件
                    $goods_dispatch = 0;
                }else{
                    //按件 每件一次
                    $goods_dispatch = $goods['dispatch_price']*$item['num'];
                }
                $last_num += $item['num'];
                if($maxbuy>0 && $last_num>$maxbuy){
                    throw new  UserException('商品'.$item['title'].'，每次限购'.$maxbuy.'件！');
                }
                if($allbuy>0){
                    if(($last_num+$userAllBuy)>$allbuy){
                        throw new  UserException('商品'.$item['title'].'，每人限购'.$allbuy.'件！');
                    }
                }
            }else{
                //和上一件不是同一商品 不考虑规格
                $goods_id=$item['goods_id'];
                if($goods['dispatch_type']==1){
                    //统一运费 多件只取一件
                    $goods_dispatch = $goods['dispatch_price'];
                }else{
                    //按件 每件一次
                    $goods_dispatch = $goods['dispatch_price']*$item['num'];
                }
                if($maxbuy>0 && $item['num']>$maxbuy){
                    throw new  UserException('商品'.$item['title'].'，每次限购'.$maxbuy.'件！');
                }
                $last_num=$item['num'];
                if($allbuy>0){
                    $userAllBuy = self::userAllBuy($user['id'],$item['goods_id']);
                    if(($item['num']+$userAllBuy)>$allbuy){
                        throw new  UserException('商品'.$item['title'].'，每人限购'.$allbuy.'件！');
                    }
                }
            }

            //可用购物积分 每件价格*抵扣比例*件数
//            $maxCoin += $item['price']*$item['can_coin']/100*$item['num'];

            //总运费
            $dispatch_price += $goods_dispatch;

//            if($item['is_vip']){
//                //有一件商品可升级vip 订单即可升级
//                $is_vip = 1;
//                $item['send_coin'] =  round($item['price']*$goods['send_coin']/100*$item['num'],2);
//                $send_coin += $item['send_coin'];
//                $item['send_sugar'] =  round($item['price']*$goods['send_sugar']/100*$item['num'],2);
//                $send_sugar += $item['send_sugar'];
//            }
        }

//        $maxCoin = round($maxCoin,2);

//        $rate = Settings::getRate();
//        if($dispatch_price>0 && $rate['is_full_free']==1){
//            if($goods_price>=$rate['full_money']){
//                $dispatch_price = 0;
//            }
//        }

        //订单总价 不使用 购物积分
        $no_use_coin_price = $goods_price+$dispatch_price;
//        $use_coin = self::calUseCoin($maxCoin,$user['coin'],$no_use_coin_price);//可以用多少购物积分
        $use_coin = 0;//可以用多少购物积分
        $use_coin_price = $no_use_coin_price-$use_coin;//购物积分抵扣后订单总价  总价 - 购物积分

        /******是否可以使用代币******/
        $pay_status = 0;
        $order = [
            'uid' => $user['id'],
            'order_sn'=>self::generateOrderSn(),
            'status'=>$pay_status,
            'num'=>$goods_total,//商品总数
            'goods_price'=>$goods_price,
            'dispatch_price'=>$dispatch_price,
            'total_price'=>$no_use_coin_price,
            'coin'=>$use_coin,
            'money'=>$use_coin_price,
            'create_time'=>now_datetime(),
            'send_name'=>$addArr['name'],
            'send_mobile'=>$addArr['mobile'],
            'send_address'=>$addArr['pca'].' '.$addArr['detail'],
            'message'=>remove_all_tags2($message),
            'proid'=>$addArr['pro_id'],
            'cityid'=>$addArr['city_id'],
            'areaid'=>$addArr['area_id'],
            'is_vip'=>$is_vip,
            'send_coin'=>$send_coin,
            'send_sugar'=>$send_sugar
        ];

        $order_id = Db::name('sell_order')->insertGetId($order);

        $delid = [];
        foreach ($data as &$item){
            $item['orderid'] = $order_id;

            if($type==1){
                //购物车
                array_push($delid,$item['car_id']);
                unset($item['car_id']);
            }
            $item['uid'] = $user['id'];
            //减库存
            Db::name('sell_goods')->where('id',$item['goods_id'])->setDec('stock',$item['num']);
            if(!empty($item['spec_id'])){
                Db::name('sell_goods_spec')->where('id',$item['spec_id'])->setDec('stock',$item['num']);
            }
        }

        unset($item);
        if($type==1){
            //清购物车
            Db::name('sell_goods_car')
                ->where('uid',$user['id'])
                ->where('id','in',$delid)
                ->delete();
        }

        //添加订单商品附表
        Db::name('sell_order_goods')->insertAll($data);

        //扣购物积分
        if($use_coin>0){
//            Money::addDelCoin($user['id'],$use_coin,2,'购物抵扣',3,$order_id,$user['id']);
        }

        $arr = [
            'status'=>1,//需要去支付
            'order_id'=>$order_id,
            'order_sn'=>$order['order_sn'],
            'money'=>$order['money']
        ];
        if($arr['money']<=0){
            //不需要支付
            $res = self::orderPay($user,$order_id,0);
            $arr['status'] = 0;
        }
        return $arr;
    }

    /**
     * 生成订单编号
     * @return string
     */
    static public function generateOrderSn()
    {
        return date("YmdHis") . random(6, true);
    }

    /**
     * 支付
     * @param $user
     * @param $order_id
     * @param $pay_type int 支付方式  1微信 2余额
     * @return array
     * @throws UserException
     * @throws \app\common\model\ServerException
     */
    static public function orderPay($user,$order_id,$pay_type,$openid=''){
        $wx = ['none'=>'none'];
        $where = [
            'id'=>$order_id,
            'uid'=>$user['id']
        ];
        $order = Db::name('sell_order')->where($where)->find();

        if(!$order){
            throw new UserException('订单找不到了！');
        }

        if($order['status']<=-1){
            throw new UserException('订单已取消，无法支付！');
        }

        if($order['status']>0){
            throw new UserException('订单已支付成功，无法重复支付！');
        }

        //是否超时
//        $rate = Settings::getRate();
//        $order_time = $rate['order_time']*60;
//        $time = now_datetime();
//        $finish_time = $order['create_time']+$order_time;
//        if($time>$finish_time){
//            throw new UserException('订单已超时'.$rate['order_time'].'分钟，请取消订单后，重新下单！');
//        }

        if($order['money']<=0){
            //不需要支付
            $change = [
                'status'=>1,
                'pay_money'=>$order['money'],
                'pay_type'=>0,
                'pay_time'=>now_datetime()
            ];
            $save = Db::name('sell_order')->where('id',$order['id'])->update($change);
            if(!$save){
                throw new ServerException('服务器繁忙，稍后再试');
            }
            $order = array_merge($order,$change);

            //增加商品销量
            self::add_sales_nums($order['id']);

//            $contro = self::rebate($order);

        }else{
            //需要支付
            if($pay_type==1){
                //微信公众号支付
                if(empty($openid)){
                    throw new DeveloperException('会员支付参数openid缺失');
                }
//                $wx = Pay::weixinJsPay($order['order_sn'],$order['money'],'购物支付','',$openid);
            }elseif($pay_type==2){
                //余额支付
//                Money::addDelMoney($user['id'],$order['money'],2,'购物支付',2,$order['id'],$user['id']);
                if($user['mybot']<$order['money']){
                    throw new UserException('SCB数量不足');
                }else{
                    \db('user')->where('id', $user['id'])->setDec('mybot', $order['money']);
                    $log_data = [
                        'uid'=>$user['id'],
                        'isadd'=>2,
                        'nums'=>$order['money'],
                        'ctime'=>now_datetime(),
                        'info'=>'商城购物支付'
                    ];
                    \db('mybot')->insert($log_data);
                }
                $change = [
                    'status'=>1,
                    'pay_money'=>$order['money'],
                    'pay_type'=>2,
                    'pay_time'=>now_datetime()
                ];
                $save = Db::name('sell_order')->where('id',$order['id'])->update($change);
                if(!$save){
                    throw new ServerException('服务器繁忙，稍后再试');
                }
                $order = array_merge($order,$change);

                //增加商品销量
                self::add_sales_nums($order['id']);

//                $contro = self::rebate($order);

            }else{
                throw new UserException('请选择支付方式');
            }
        }

        $arr = [
            'order_id'=>$order['id'],
            'pay_type'=>$pay_type,
            'wx'=>$wx,
            'order_sn'=>$order['order_sn']
        ];

        return $arr;
    }

    /**
     * 订单列表
     * @param $user_id
     * @param int $type
     * @param int $page
     * @param int $page_size
     * @return false|\PDOStatement|string|\think\Collection
     * @throws DeveloperException
     */
    static public function orderList($user_id,$type=0,$page=1,$page_size=10){

        $where['uid'] = $user_id;
        $where['is_valid']=1;
        switch ($type){
            case 0:
                //待付款
                $where['status']=0;
                $str = '需付款';
                break;
            case 1:
                //待发货
                $where['status']=1;
                $str = '实付款';
                break;
            case 2:
                //待收货
                $where['status']=2;
                $str = '实付款';
                break;
            case 3:
                //已完成
                $where['status']=3;
                $str = '实付款';
                break;
            case -1:
                //已取消
                $where['status']=['lt',0];
                $str = '需付款';
                break;
            default:
                throw new DeveloperException('无此订单类型');
                break;

        }

        $list = Db::name('sell_order')
            ->order('id DESC')
            ->field('id,order_sn,status,num,money')
            ->page($page,$page_size)
            ->where($where)
            ->select();

        foreach ($list as &$item){
            $item['data'] = Db::name('sell_order_goods')
                ->where('orderid',$item['id'])
                ->field('id as order_goods_id,goods_id,title,img_url,spec_title,is_comment, price,num')
                ->select();
            $item['str'] = $str;
        }

        return $list;
    }


    /**
     * 删除订单 软删除
     * @param $user_id
     * @param $order_id
     * @return string
     */
    static public function orderRemove($user_id,$order_id){

        $del = Db::name('sell_order')
            ->where('id',$order_id)
            ->where('uid',$user_id)
            ->where('status >= 3 OR is_CANCLE >= 1')
            ->update(['is_valid'=>0]);
        if($del){
            return '订单删除成功！';
        }else{
            throw new UserException('仅可删除已完成或已取消的订单！');
        }
    }

    /**
     * 取消订单
     * @param $user_id
     * @param $order_id
     * @return string
     */
    static public function orderCancel($user,$order_id){
        $coin_title = config('coin_title');
        $user_id = $user['id'];
        $where = [
            'id'=>$order_id,
            'uid'=>$user_id
        ];
        $order = Db::name('sell_order')
            ->where($where)
            ->find();

        if(!$order){
            throw new UserException('无此订单！');
        }

        if($order['status']>0){
            throw new UserException('已支付成功，无法取消订单！');
        }

        $data = [
            'status'=>-1
        ];

        $save = Db::name('sell_order')->where($where)->update($data);
        if(!$save){
            throw new ServerException('服务器繁忙，请稍后再试');
        }

        $goods = Db::name('sell_order_goods')->where('orderid',$order_id)->select();
        foreach ($goods as $item){
            Db::name('sell_goods')->where('id',$item['goods_id'])->setInc('stock',$item['num']);
            if(!empty($item['spec_id'])){
                Db::name('sell_goods_spec')->where('id',$item['spec_id'])->setInc('stock',$item['num']);
            }
        }

        if($order['money']>0){
            //退还SCB
//            Money::addDelCoin($user['id'],$order['coin'],1,'购物订单取消，积分退回',4,$order_id);
            \db('user')->where('id', $user['id'])->setInc('mybot', $order['money']);
            $log_data = [
                'uid'=>$user['id'],
                'isadd'=>1,
                'nums'=>$order['money'],
                'ctime'=>now_datetime(),
                'info'=>'商城订单取消'
            ];
            \db('mybot')->insert($log_data);

        }

        return '订单取消成功';
    }

    /**
     * 订单详情
     * @param $user_id
     * @param $order_id
     * @return array
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static public function orderInfo($user_id='',$order_id='',$order_sn='',$from=1){
        $where = [];
        if(empty($order_id)&&empty($order_sn)){
            throw new UserException('参数有误');
        }
        if(!empty($user_id)){
            $where['uid'] = $user_id;
        }
        if(!empty($order_id)){
            $where['id']=$order_id;
        }
        if(!empty($order_sn)){
            $where['order_sn']=$order_sn;
        }
        $order = Db::name('sell_order')
            ->where($where)
            ->find();

        if(!$order){
            throw new UserException('无此订单！');
        }
        if($from==1){
            if($order['is_valid']!=1){
                throw new UserException('订单已删除！');
            }
            if($order['status']<0){
                throw new UserException('订单已取消！');
            }
        }
//        $global = Settings::getSettings(H_SETTINGS_GLOBAL,2);

        switch ($order['status']){
            case 0:
                $status_str = '待付款';
//                $order_time = Settings::getRate('order_time');
//                $desc_str = '您的订单已提交，请在'.$order_time.'分钟内完成支付，超时订单将取消';
                $desc_str = '您的订单已提交，请尽快提交';
                $status_str_two = '待付款，请付款';
                $status_img = get_status_img(0);
                $status_time = accurateDate($order['create_time']);
                $pay_time = '';
                break;

            case 1:
                $status_str = '待发货';
                $desc_str = '您的订单正在出库，请耐心等待';
                $status_str_two = '包裹正在出库中';
                $status_img = get_status_img(1);
                $status_time = accurateDate($order['pay_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case 2:
                $status_str = '发货中';
                $desc_str = '您的订单正在路上，请耐心等待';
                $status_str_two = '包裹正在路上';
                $status_img = get_status_img(2);
                $status_time = accurateDate($order['send_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case 3:
                $status_str = '已完成';
                $desc_str = '您的订单已完成，感谢您的支持';
                $status_str_two = '订单已完成';
                $status_img = get_status_img(3);

                $status_time = accurateDate($order['receive_time']);
                $pay_time = accurateDate($order['pay_time']);
                break;
            case -1:
                $status_str = '已取消';
                $desc_str = '您的订单已取消';
                $status_str_two = '订单已取消';
                $status_img = get_status_img(3);

                $status_time = '';
                $pay_time = '';
                break;
            default:
                throw new UserException('订单信息有误！');
                break;
        }

        if($order['status']<=0){
            $pay_type = '';
        }else{
            if($order['pay_type']==1){
                $pay_type = '微信';
            }elseif($order['pay_type']==2){
                $pay_type = 'SCB';
            }else{
                $pay_type = '';
            }

            if($order['coin']>0){

                if(empty($pay_type)){
                    $pay_type = config('coin_title');
                }else{
                    $pay_type .= '+'.config('coin_title');
                }
            }

        }

        $data = Db::name('sell_order_goods')
            ->where('orderid',$order['id'])
            ->field('id as _id,goods_id,title,img_url,spec_title,price,can_coin,num,is_vip,send_coin,send_sugar,is_comment')
            ->select();

        $arr = $order;
        $arr['status_str']=$status_str;
        $arr['desc_str']=$desc_str;
        $arr['status_str_two']=$status_str_two;
        $arr['status_img']=$status_img;
        $arr['status_time']=$status_time;
        $arr['data']=$data;
        $arr['pay_type']=$pay_type;
        $arr['create_time']=accurateDate($arr['create_time']);
        $arr['pay_time']=$pay_time;
        return $arr;
    }

    /**
     * 订单确认收货
     * @param $uid
     * @param $order_id
     * @return string
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    static public function orderReceive($uid,$order_id){

        $where = [
            'id'=>$order_id,
            'uid'=>$uid
        ];

        $order = Db::name('sell_order')
            ->where($where)
            ->find();

        if(!$order){
            throw new UserException('无此订单记录');
        }
        if($order['status']<=-1){
            throw new UserException('订单已取消！');
        }
        if($order['is_valid']!=1){
            throw new UserException('订单已删除！');
        }

        if($order['status']<2){
            throw new UserException('订单还未发货，无法确认收货');
        }
        if($order['status']>=3){
            throw new UserException('订单已收货，无法重复收货');
        }
        //需要确认收货
        $data = [
            'status'=>3,
            'receive_time'=>now_datetime()
        ];

        $res = Db::name('sell_order')
            ->where('id',$order['id'])
            ->update($data);
        if(!$res){
            throw new ServerException('数据库繁忙请稍后再试');
        }

        return '确认收货成功！';
    }

    /**
     * 增加销量
     */
    static public function add_sales_nums($orderid){
        $list = Db::name('sell_order_goods')
            ->where('orderid',$orderid)
            ->field('goods_id,num')
            ->select();
        foreach ($list as $item){
            Db::name('sell_goods')->where('id',$item['goods_id'])->setInc('sales_nums',$item['num']);
            Db::name('sell_goods')->where('id',$item['goods_id'])->setInc('real_sales',$item['num']);
        }
    }

    /**
     * 订单返利计算
     * @param $order
     */
    static public function rebate($order){
        return true;
        $order = Db::name('sell_order')
            ->where('id',$order['id'])
            ->find();

        if(config('return_type')==1){
            $jichu = $order['total_price'];
        }else{
            $jichu = $order['goods_price'];
        }

        if(!$order){
            throw new ServerException('无此订单');
        }
        if($order['is_return']==1){
            throw new ServerException('订单参数有误');
        }
        $user = Db::name('sell_user')
            ->where('id',$order['uid'])
            ->find();
        if(!$user){
            throw new ServerException('用户信息有误');
        }
//        if($order['send_coin']>0){
//            //赠送购物积分
//            Money::addDelCoin($user['id'],$order['send_coin'],1,'购VIP赠送',2,$order['id'],$order['uid']);
//        }
//        if($order['send_sugar']>0){
//            //赠送消费积分
//            Money::addDelSugar($user['id'],$order['send_sugar'],1,'购VIP赠送',2,$order['id'],$order['uid']);
//        }

        $change=['is_return'=>1];

        $rate = Settings::getRate();
        //买家上一级
        if($user['parent_id']>0){
            $parent = Db::name('user')
                ->where('id',$user['parent_id'])
//                ->where('in_blacklist',0)
                ->find();
            if($parent){
                if($parent['identity']<=1){
                    $bili = $rate['up_nor1'];
                }else{
                    $bili = $rate['up_vip1'];
                }
                $money1 = cut_two($bili*$jichu/100);
                if($money1>0){
                    $change['up1_id']=$parent['id'];
                    $change['up1_price']=$money1;
                    Money::addDelSugar($parent['id'],$money1,1,'一级好友【'.show_star($user['mobile']).'】，线上购物返利',4,$order['id'],$user['id']);
                }
            }
        }
        //买家上二级
        if($user['parent_id2']>0){
            $parent2 = Db::name('user')
                ->where('id',$user['parent_id2'])
//                ->where('in_blacklist',0)
                ->find();
            if($parent2){
                if($parent2['identity']<=1){
                    $bili = $rate['up_nor2'];
                }else{
                    $bili = $rate['up_vip2'];
                }
                $money2 = cut_two($bili*$jichu/100);
                if($money2>0){
                    $change['up2_id']=$parent2['id'];
                    $change['up2_price']=$money2;
                    Money::addDelSugar($parent2['id'],$money2,1,'二级好友【'.show_star($user['mobile']).'】，线上购物返利',4,$order['id'],$user['id']);
                }
            }
        }

        Db::name('order')
            ->where('id',$order['id'])
            ->update($change);

        return true;
    }



    /**
     * 支付验证 app端 暂无用
     * @param $user
     * @param $order_sn
     * @param $pay_type
     * @return array
     */
    static public function orderCheck($user,$order_sn,$pay_type){
        $status = 0;
        $str = '';

        $order = Db::name('order')
            ->where('order_sn',$order_sn)
            ->find();
        if(!$order){
            throw new UserException('无此订单');
        }

        if($pay_type==1)
        {
            $weixn= new WeixinPay();
            $status=$weixn->getPayStatus($order_sn);
        }elseif ($pay_type==2)
        {
            $ali=new AliPay();
            $status=$ali->getPayStatus($order_sn);
        }

        if($status==1){
            $str = '恭喜付款成功了';
        }else{
            $str = '很抱歉付款失败了';
        }

        $arr = [
            'status'=>$status,
            'str'=>$str
        ];
        return $arr;
    }

    /**
     * 订单评价 暂无用
     * @param $user_id
     * @param $order_goods_id
     * @param $star
     * @param $content
     * @return string
     * @throws UserException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    static public function orderComment($user_id,$order_goods_id,$star,$content){

        $order_goods = Db::name('order_goods')
            ->alias('og')
            ->join('__ORDER__ o','o.id=og.orderid')
            ->where('og.id',$order_goods_id)
            ->where('og.uid',$user_id)
            ->field('og.*,status')
            ->find();

        $star = intval($star);
        if(empty($star)||$star>5){
            throw new UserException('评分只能1-5星！');
        }

        $content = remove_all_tags($content);
        if(empty($content)){
            throw new UserException('请输入评价内容！');
        }

        if(!$order_goods){
            throw new  UserException('您的订单中无此购买记录，无法评价！');
        }
        if($order_goods['is_comment']==1){
            throw new  UserException('此商品已评价，请不要重复评价！');
        }
        if($order_goods['status']<3){
            throw new  UserException('还未确认收货，无法评价！');
        }

        $data = [
            'uid'=>$user_id,
            'order_id'=>$order_goods['orderid'],
            'business_id'=>$order_goods['business_id'],
            'goods_id'=>$order_goods['goods_id'],
            'spec_id'=>$order_goods['spec_id'],
            'spec_title'=>$order_goods['spec_title'],
            'star'=>$star,
            'content'=>$content,
            'comment_time'=>now_datetime()
        ];
        Db::name('goods_comment')->insert($data);
        Db::name('order_goods')->where('id',$order_goods_id)->update(['is_comment'=>1]);
        return '评价提交成功！';
    }

}

